<template>
  <a-modal
    :zIndex="zIndex"
    :title="title"
    :visible="visible"
    @cancel="handleCancel"
    width="850px"
    :cancelText="$t('关闭')"
    :confirmLoading="confirmLoading"
    v-drag
  >
    <template slot="footer">
      <a-row :gutter="24">
        <a-col :span="12">
          <div style="text-align: left" v-if="!dataForm.id">
            <a-checkbox v-model="isContinue" @change="changeAddState"></a-checkbox> {{ $t('连续添加') }}
          </div>
        </a-col>
        <a-col :span="12">
          <a-button @click="handleCancel" :disabled="confirmLoading">{{ $t('取消') }}</a-button>
          <a-button type="primary" @click="handleOk" v-if="!disable" :disabled="confirmLoading">{{
            $t('保存')
          }}</a-button>
        </a-col>
      </a-row>
    </template>
    <div style="height: 600px; overflow-y: auto">
      <a-row style="margin-left: 10px">
        <a-col :span="24">
          <a-form-model
            ref="dataForm"
            :rules="rules"
            :model="dataForm"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
            v-enterToNext
          >
            <a-row>
              <div style="margin: 0 0 10px -10px; color: black; font-weight: 500; font-size: 15px">
                {{ $t('基本信息') }}
              </div>
              <a-col :span="12">
                <a-form-model-item prop="code" style="margin-bottom: 10px" :label="$t('商品编码')">
                  <a-input v-model="dataForm.code" ref="code" :disabled="disable"></a-input>
                </a-form-model-item>
                <a-form-model-item prop="name" style="margin-bottom: 10px" :label="$t('商品名称')">
                  <a-input v-model="dataForm.name" :disabled="disable"></a-input>
                </a-form-model-item>
                <a-form-model-item prop="kind" style="margin-bottom: 10px" :label="$t('商品分类')">
                  <a-tree-select
                    show-search
                    :filterTreeNode="filterTreeNode"
                    :disabled="disable"
                    allowClear
                    v-model="dataForm.kind"
                    :dropdownStyle="{ maxHeight: '250px', overflow: 'auto' }"
                    :tree-data="treeData"
                    :placeholder="$t('请选择')"
                    :getPopupContainer="triggerNode => { return triggerNode.parentNode || document.body }"
                  />
                </a-form-model-item>
                <a-form-model-item prop="realCoin" style="margin-bottom: 10px" :label="$t('币值')">
                  <a-input-number v-model="dataForm.realCoin" :disabled="disable"

                                  :formatter="formatter"
                                  :parser="parser"
                                  style="width: 100%;"
                  ></a-input-number>
                </a-form-model-item>
                <a-form-model-item prop="price" style="margin-bottom: 10px" :label="$t('售价')">
                  <a-input-number v-model="dataForm.price" :disabled="disable" @change="changePrice"

                                  :formatter="formatter"
                                  :parser="parser"
                                  style="width: 100%;"
                                  :precision="2"
                  ></a-input-number>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-col :span="24" style="padding-right: 0">
                  <a-form-model-item
                    prop="picture"
                    :label="$t('图片')"
                    :labelCol="{ span: 3 }"
                    :wrapperCol="{ span: 18 }"
                  >
                    <div>
                      <j-upload v-model="dataForm.picture" accept="jpg,jpeg,png,gif,webp" fileType="image" :disabled="disable"></j-upload>
                      <div style="color: #f7b926; line-height: 1.2">
                        {{ $t('建议尺寸：750*750，大小不要超过500KB') }}
                      </div>
                    </div>
                  </a-form-model-item>
                </a-col>
              </a-col>
              <a-col :span="24">
                <a-form-model-item
                  prop="comment"
                  :labelCol="{ span: 3 }"
                  :wrapperCol="{ span: 18 }"
                  :label="$t('备注')"
                >
                  <a-textarea v-model="dataForm.comment" ref="comment" :rows="3" :disabled="disable" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row style="margin-left: 20px" v-if="taxSetting != 0">
              <div style="margin: 10px 0 10px -30px; color: black; font-weight: 500; font-size: 15px">
                {{ $t('销售设置') }}
              </div>
              <a-col :span="24">
                <a-row>
                  <a-col :span="8" v-if="taxSetting == 1">
                    <a-form-model-item prop="allowTax" style="margin-bottom: 5px;margin-left: 10px" :labelCol="{ span: 0 }" :wrapperCol="{ span: 22 }">
                      <a-checkbox :checked="dataForm.allowTax == 1" :disabled="disable" @change="changeSelectState">{{
                        $t('销售加税')
                      }}</a-checkbox>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="8" v-if="taxSetting == 2">
                    <a-form-model-item
                      prop="allowTax"
                      style="margin-bottom: 5px; margin-left: 10px"
                      :labelCol="{ span: 0 }"
                      :wrapperCol="{ span: 24 }"
                    >
                      {{$t('其中税费')}}：{{ dataForm.taxPrice }}
                    </a-form-model-item>
                  </a-col>
                </a-row>
              </a-col>
            </a-row>
            <a-row style="margin-left: 20px">
              <div style="margin: 10px 0 10px -30px; color: black; font-weight: 500; font-size: 15px">
                {{ $t('更多设置') }}
              </div>
              <a-row>
                <a-col :span="2">{{ $t('有效期') }}:</a-col>
                <a-col>
                  <a-form-model-item prop="validityType" :wrapper-col="{span: 20}">
                    <a-radio-group v-model="dataForm.validityType" ref="validityType">
                      <div>
                        <a-radio value="0" style="width: 88px" :disabled="disable">{{ $t('不限期') }}</a-radio>
                      </div>
                      <div>
                        <a-radio value="1" style="width: 88px" :disabled="disable">{{ $t('指定日期') }}：</a-radio>
                        <j-date
                          :disabled="dataForm.validityType != '1'"
                          v-model="dataForm.startDate"
                          :placeholder="$t('请选择日期')"
                          style="width: 180px"
                        ></j-date>
                        ~
                        <j-date
                          :disabled="dataForm.validityType != '1'"
                          v-model="dataForm.endDate"
                          :placeholder="$t('请选择日期')"
                          style="width: 180px"
                        ></j-date>
                      </div>
                      <div style="margin-top: 20px">
                        <a-radio value="2" style="width: 88px" :disabled="disable">{{ $t('指定时长') }}：</a-radio>
                        {{ $t('领取后') }}
                        <a-input-number
                          :disabled="dataForm.validityType != '2'"
                          v-model="dataForm.startDays"
                          style="width: 80px; margin-right: 10px"
                          :min="0"
                          :formatter="formatter"
                          :parser="parser"

                        ></a-input-number>
                        {{ $t('天生效 ，有效期') }}
                        <a-input-number
                          :disabled="dataForm.validityType != '2'"
                          v-model="dataForm.validDays"
                          style="width: 80px; margin-right: 10px; margin-left: 10px"
                          :min="0"
                          :formatter="formatter"
                          :parser="parser"
                        ></a-input-number>
                        <a-select class="cus-select1" v-model="dataForm.timeUnit"
                          style="width:80px;color: rgba(245, 27, 7, 0.68);"
                          :disabled="dataForm.validityType != '2'">
                          <a-select-option v-for="item in timeUnitList" :key="item.value" :value="item.value">
                            {{ item.title }}
                          </a-select-option>
                        </a-select>
                      </div>
                    </a-radio-group>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="9">
                  <a-form-model-item prop="state" style="margin-bottom: 5px" :label="$t('上架状态')">
                    <a-radio-group v-model="dataForm.state" ref="state" :disabled="disable">
                      <a-radio value="Y">{{ $t('上架') }}</a-radio>
                      <a-radio value="N">{{ $t('下架') }}</a-radio>
                    </a-radio-group>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col>
                  <a-form-model-item
                    prop="allowGame"
                    :labelCol="{ span: 2 }"
                    :wrapperCol="{ span: 20 }"
                    style="margin-bottom: 5px; margin-left: 4px"
                    :label="$t('适用项目')"
                  >
                    <a-radio-group
                      v-model="allowGame"
                      @change="getGameValue"
                      :disabled="disable"
                      style="margin-left: 5px"
                    >
                      <a-radio value="">{{ $t('全部') }}</a-radio>
                      <a-radio value="part">{{ $t('指定项目') }}</a-radio> </a-radio-group
                    ><br />
                    <div style="margin-top: 6px; margin-left: 5px" v-if="gameShow">
                      <a-checkbox
                        style="width: 70px; margin-top: -10px"
                        v-model="selectAll"
                        :disabled="disable"
                        @change="switchSelect"
                        >{{$t('全选')}}</a-checkbox
                      >
                      <div v-for="(ele, i) in gamegroups" :key="i">
                        <a-checkbox
                          style="margin-top: -10px"
                          v-model="ele.isSelect"
                          :disabled="disable"
                          @change="(e)=>switchSelect1(e,i)"
                          >{{ele.code+'-'+ele.name}}</a-checkbox
                        >
                        <div>
                          <a-checkbox-group v-model="ele.allowGames" :disabled="disable" @change="changeGame">
                            <a-checkbox style="margin-left: 8px" :value="item.id" v-for="item in ele.gameList" :key="item.id">{{
                              item.name
                            }}</a-checkbox>
                          </a-checkbox-group>
                        </div>
                      </div>
                    </div>
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-row>
          </a-form-model>
        </a-col>
      </a-row>
    </div>
  </a-modal>
</template>

<script>
import Vue from 'vue'
import { TENANT_ID } from '@/store/mutation-types'
import { initDictOptions } from '@/components/dict/JDictSelectUtil'
import { httpAction, getAction } from '@/api/manage'
import {formatter, parser} from "@api/comm";

export default {
  name: 'TimeLimitCoinModal',
  components: {},
  data() {
    return {
      formatter,
      parser,
      zIndex: 1001,
      form: this.$form.createForm(this),
      title: '',
      visible: false,
      confirmLoading: false,
      dataForm: {
        code: '',
        name: '',
        allowOuts: '',
        allowWarns: '',
        warnNum: 0,
        verifyType: '1',
        allowTax: 1,
        allowMemberDiscounts: '',
        allowCoins: '',
        allowLotterys: '',
        allowPointss: '',
        allowSale: 'Y',
        allowIntegrals: '',
        allowAlotterys: '',
        state: '',
        allowMemberType: '',
        allowDeviceType: '',
        allowDevice: '',
        allowGame: '',
        form: '', //形态
        validityType: '0',
      },
      labelCol: {
        xs: { span: 20 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 20 },
        sm: { span: 15 },
      },
      rules: {
        name: [{ required: true, message: this.$t('请输入卖品名称') }],
        kind: [{ required: true, message: this.$t('请选择卖品分类') }],
        realCoin: [
          { required: true, message: this.$t('请输入币值') },
          { pattern: /^\d+.?\d{0,2}$/, message: this.$t('小数点后最多输入两位') },
        ],
        price: [
          { required: true, message: this.$t('请输入售价') },
          { pattern: /^\d+.?\d{0,2}$/, message: this.$t('小数点后最多输入两位') },
        ],
      },
      url: {
        add: '/goods/bisGoodsInfor/add',
        edit: '/goods/bisGoodsInfor/edit',
        importExcelUrl: '/sys/common/upload',
      },
      disable: false,
      treeData: [],
      gameShow: false,
      gamegroups: [],
      allowGame: '',
      allowGames: [],
      timeUnitList: [],
      islimitValid: false,
      isContinue: true,
      selectAll: false,
      tenantid: Vue.ls.get(TENANT_ID),
      taxSetting: 0,
    }
  },
  mounted() {},
  created() {
    this.initDictConfig()
  },
  methods: {
    initDictConfig() {
      initDictOptions('bis_goods_infor.time_unit').then((res) => {
        if (res.success) {
          this.timeUnitList = res.result
        }
      })
    },
    add(value) {
      this.visible = true
      this.isContinue = localStorage.getItem('goodsAddInfo')
        ? JSON.parse(localStorage.getItem('goodsAddInfo')).state
        : true
      this.selectAll = false
      this.dataForm = {
        code: '',
        name: '',
        allowOut: 'Y',
        allowWarns: '',
        warnNum: 0,
        verifyType: '1',
        cost: 0,
        allowTax: 1,
        allowMemberDiscount: 'Y',
        allowCoins: '',
        allowLotterys: '',
        allowPointss: '',
        allowSale: 'Y',
        allowIntegrals: '',
        allowAlotterys: '',
        state: 'Y',
        allowMemberType: '',
        allowDevice: '',
        allowDeviceType: '',
        allowGame: '',
        form: value,
        presentCoin: '0',
        realCoin: '',
        species: '1',
        validityType: '0',
      }
      this.edit(this.dataForm)
    },
    async edit(record, state) {
      this.disable = state
      this.allowGames = []
      this.visible = true
      await this.getGameList()
      this.select()
      this.taxSetting = localStorage.getItem('taxSetting')
      this.allowGame = record.allowGame
      if (this.allowGame == '' || this.allowGame == null || this.allowGame == undefined) {
        this.gameShow = false
      } else {
        this.allowGames = record.allowGame.split(',')
        this.allowGame = 'part'
        this.gameShow = true
      }
      this.$nextTick(() => {
        this.gamegroups.forEach((g, i) => {
          g.allowGames = []
          g.gameList.forEach(l => {
            let x = this.allowGames.findIndex(a => {return a == l.id})
            if(x > -1){
              g.allowGames.push(l.id)
            }
          })
          g.isSelect = g.allowGames.length == g.gameList.length ? true : false
        })
        record.timeUnit = record.timeUnit !== undefined ? ('' + record.timeUnit) : '0'
        this.dataForm = Object.assign({}, record)
      })
    },
    filterTreeNode(inputValue, treeNode) {
      // 假设输入格式为 "级别:关键词" 如 "2:电器"
      const match = inputValue.match(/([123]):(.+)/)
      if (match) {
        const level = parseInt(match[1])
        const keyword = match[2]
        const nodeLevel = this.getNodeLevel(treeNode)
        
        if (nodeLevel !== level) return false
        return treeNode.data.props.title.includes(keyword)
      }
      
      // 默认搜索
      return treeNode.data.props.title.includes(inputValue)
    },
    getNodeLevel(node) {
      let level = 1
      let parent = node.parent
      while (parent) {
        level++
        parent = parent.parent
      }
      return level
    },
    select() {
      let that = this
      let param = {}
      param.pageNo = 1
      param.pageSize = 9999
      param.column = 'sort'
      param.order = 'asc'
      if(!that.disable && !that.tenantid){
        param.tenantId = 0
      }
      getAction('/goods/bisGoodsKind/rootList', param).then((res) => {
        if (res.success) {
          if (res.result.records.length > 0) {
            res.result.records.forEach((col) => {
              col.key = '' + col.id
              col.value = '' + col.id
              col.title = '' + col.name
              col.id = '' + col.id
              col.pid = '' + col.pid
              col.hasChild = '' + col.hasChild
              if (col.hasChild != '0') {
                that.getHasChild(col)
              }
            })
            that.treeData = that.getDataByResult(res.result.records)
          } else {
            that.treeData = []
          }
        } else {
          that.$alert(res.message, that.$t('提示'), {
            confirmButtonText: that.$t('确定'),
            callback: (action) => {},
          })
        }
      })
    },
    getHasChild(record) {
      let that = this
      let query = {}
      query.pageNo = 1
      query.pageSize = 9999
      query.pid = record.id
      if(!that.disable && !that.tenantid){
        query.tenantId = 0
      }
      getAction('/goods/bisGoodsKind/rootList', query).then((res) => {
        if (res.success) {
          if (res.result.records.length > 0) {
            res.result.records.forEach((col) => {
              col.key = '' + col.id
              col.value = '' + col.id
              col.title = '' + col.name
              col.pid = '' + col.pid
              col.id = '' + col.id
              col.hasChild = '' + col.hasChild
              if (col.hasChild != '0') {
                that.getHasChild(col)
              }
            })
            record.children = that.getDataByResult(res.result.records)
            that.treeData = [...that.treeData]
          }
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    getDataByResult(result) {
      return result.map((item) => {
        return item
      })
    },
    getGameValue(e) {
      if (e.target.value == 'part') {
        this.gameShow = true
      } else {
        this.gameShow = false
      }
    },
    getGameList() {
      return new Promise(resolve=>{
        let that = this
        getAction('game/bisGame/shopList', {}).then((res) => {
          if (res.success) {
            that.gamegroups = res.result 
          }
          resolve()
        })
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    orgData(list,i,arr){
      return new Promise(resolve=>{
        if(i<list.length){
          arr = [...arr,...list[i]]
          i++
          this.orgData(list,i,arr)
        }else{
          this.allowGames = arr.join(',')
          resolve()
        }
      })
    },
    handleOk() {
      let that = this
      let querydata = {}
      that.$refs.dataForm.validate((valid) => {
        if (valid) {
          if (that.allowGame == 'part') {
            let arrs = []
            that.gamegroups.map(g=>{return g.allowGames}).forEach(a=>{
              arrs = [...arrs,...a]
            })
            if (arrs.length == 0) {
              that.$message.warn(that.$t('请选择适用项目'))
              return
            }
            that.dataForm.allowGame = arrs.join(',')
          } else {
            that.dataForm.allowGame = ''
          }
          querydata = that.dataForm
          let httpurl = ''
          let method = ''
          if (!that.dataForm.id) {
            httpurl += that.url.add
            method = 'post'
          } else {
            httpurl += that.url.edit
            method = 'put'
          }
          that.confirmLoading = true
          httpAction(httpurl, querydata, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
                if (that.dataForm.id || !that.isContinue) {
                  that.close()
                } else {
                  that.initDataForm()
                }
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
    handleCancel() {
      this.close()
    },
    changeAddState() {
      localStorage.setItem('goodsAddInfo', JSON.stringify({ state: this.isContinue }))
    },
    initDataForm() {
      this.selectAll = false
      this.dataForm = {
        code: '',
        name: '',
        allowOut: 'Y',
        allowWarns: '',
        warnNum: 0,
        verifyType: '1',
        cost: 0,
        allowTax: 1,
        allowMemberDiscount: 'Y',
        allowCoins: '',
        allowLotterys: '',
        allowPointss: '',
        allowSale: 'Y',
        allowIntegrals: '',
        allowAlotterys: '',
        state: 'Y',
        allowMemberType: '',
        allowDevice: '',
        allowDeviceType: '',
        allowGame: '',
        form: 15,
        presentCoin: '0',
        realCoin: '',
        species: '1',
        validityType: '0',
      }
      this.$refs.code.focus()
      this.edit(this.dataForm)
    },
    switchSelect(e) {
      if (this.selectAll) {
        this.gamegroups.forEach(el=>{
          el.isSelect = true
          el.allowGames = el.gameList.map((game) => {
            return game.id
          })
        })
      }else{
        this.gamegroups.forEach(el=>{
          el.isSelect = false
          el.allowGames = []
        })
      }
    },
    switchSelect1(e,i){
      if(e.target.checked) {
        this.$set(this.gamegroups[i], 'allowGames', this.gamegroups[i].gameList.map((game) => {
          return game.id
        }))
      } else {
        this.$set(this.gamegroups[i], 'allowGames', [])
      }
      this.$forceUpdate()
    },
    changeGame(e){
      this.$forceUpdate()
    },
    changeSelectState(e){
      this.$set(this.dataForm, "allowTax", e.target.checked ? 1 : 0)
    },
    changePrice() {
      if(this.taxSetting == 2){
        this.$set(this.dataForm,'taxPrice',(this.dataForm.price - (this.dataForm.price / ( 1 + localStorage.getItem('taxRate') / 100))).toFixed(2))
      }
    },
  },
}
</script>
<style scoped>
.bold-font {
  font-weight: bold;
}
/deep/ .cus-select1 .ant-select-selection{
  border-color: rgba(245, 27, 7, 0.68);
}
/deep/ .detail-upload .ant-upload-list-picture-card-container {
  width: 100%;
  height: 250px;
}
/deep/ .detail-upload .ant-upload-list-picture-card .ant-upload-list-item {
  width: 77% !important;
  height: 100% !important;
}
/deep/ .detail-upload .ant-upload .ant-upload-select .ant-upload-select-picture-card {
  width: 100%;
  height: 250px;
}
/deep/ .detail-upload .ant-upload {
  width: 77% !important;
  height: 100% !important;
}
</style>